home *** CD-ROM | disk | FTP | other *** search
/ Java Primer Plus / Java Primer Plus (Waite Group Proess)(1996).iso / chapter17 / palindrome.java < prev    next >
Text File  |  1995-12-31  |  1KB  |  47 lines

  1. import java.util.Stack;
  2.  
  3. /* class palindrome */
  4. class palindrome {
  5.  
  6.   static public void main(String args[]) throws 
  7.                 java.io.IOException {
  8.     char c;
  9.     inChar i;
  10.     boolean accept = true;
  11.     Stack theStack = new Stack();
  12.  
  13.     /* read in left side of the string */
  14.     while ((c = (char)System.in.read()) != '$') {
  15.     if (theStack.empty()) theStack.push(new inChar(c));
  16.     else {
  17.       i = (inChar)theStack.peek();
  18.       if (i.accessc() != c)
  19.         theStack.push(new inChar(c));
  20.       else
  21.         i.upcount();
  22.       }
  23.     }
  24.  
  25.     /* read in right side, pop stack, and compare */
  26.     while ((c = (char)System.in.read()) != '\n') {
  27.     if (theStack.empty()) { accept = false;
  28.                 break;
  29.                 }
  30.     i = (inChar)theStack.peek();
  31.  
  32.     if (i.accessc() != c) { accept = false;
  33.                 break;
  34.                 }
  35.     else if (i.countdone()) theStack.pop();
  36.          else i.downcount();
  37.     }
  38.  
  39.     if (accept && (!theStack.empty())) accept = false;
  40.  
  41.     System.out.println();
  42.     System.out.print("Palindrome ");
  43.     if (accept) System.out.println("Accepted");
  44.     else System.out.println("Invalid");
  45.        }
  46.  }
  47.